export class Router {
    constructor() {
        this.routerHandlerMap = new Map()
    }

    _key(method, route) {
        return `${method.toUpperCase()}:${route}`
    }

    _registerRoute(method, route, handler) {
        const key = this._key(method, route)
        this.routerHandlerMap.set(key, handler)
    }

    get(route, handler) {
        this._registerRoute('GET', route, handler)
    }

    post(route, handler) {
        this._registerRoute('POST', route, handler)
    }

    matchRoute(target, pattern) {
        const targetSegments = target.split('/');
        const patternSegments = pattern.split('/');
        if (targetSegments.length !== patternSegments.length) return false;
        for (let i = 0; i < targetSegments.length; i++) {
            const t = targetSegments[i];
            const p = patternSegments[i];
            if (p.startsWith(':')) {
                if (t === '') return false;
            }
            else if (t !== p) {
                return false;
            }
        }
        return true;
    }

    getRouteHandler(method, route) {
        const key = this._key(method, route)
        // 直接匹配处理函数
        const handler = this.routerHandlerMap.get(key)
        if (handler) return handler

        // 匹配动态路由
        for (const key of this.routerHandlerMap.keys()) {
            const routePattern = key.replace(`${method.toUpperCase()}:`, '')
            const match = this.matchRoute(route, routePattern)
            if (match) return this.routerHandlerMap.get(key)
        }
        return null;
    }
}
